package com.novelot.plugin.allinone.stat;

import com.novelot.plugin.allinone.util.AppExecutors;
import com.novelot.plugin.allinone.util.Logger;
import com.novelot.plugin.allinone.util.ShellUtils;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class StatistView {

    private Object[][] rows;
    private String[] cols = {"提交者", "月份", "added lines", "removed lines", "total lines"};
    private java.util.List<StatBean> sbs = new ArrayList<>();
    private String author = "刘云龙";
    private String path = "/Users/momo/Projects/Momo/android_hanisdk/hanisdk";
    private JTextField tfPath;
    private JTextField tfAuthor;
    private JTable table;
    private DefaultTableModel tabelModel;

    public JPanel createStatistView() {

        JPanel panel = new JPanel();
        panel.setLayout(new GridBagLayout());
        //添加配置条
        JPanel configPanel = new JPanel();
        GridBagConstraints configPanelConstraints = new GridBagConstraints();
        configPanelConstraints.gridx = 1;
        configPanelConstraints.gridy = 1;
        configPanelConstraints.gridwidth = 1;
        configPanelConstraints.gridheight = 1;
        configPanelConstraints.fill = GridBagConstraints.HORIZONTAL;
        panel.add(configPanel, configPanelConstraints);


        configPanel.setLayout(new GridBagLayout());

        //项目路径
        JLabel labelPath = new JLabel("项目路径:");
        GridBagConstraints labelPathConstraints = new GridBagConstraints();
        labelPathConstraints.gridx = 1;
        labelPathConstraints.gridy = 1;
        labelPathConstraints.gridwidth = 1;
        labelPathConstraints.gridheight = 1;
        configPanel.add(labelPath, labelPathConstraints);

        tfPath = new JTextField();
        tfPath.setText(path);
        GridBagConstraints tfPathConstraints = new GridBagConstraints();
        tfPathConstraints.gridx = 2;
        tfPathConstraints.gridy = 1;
        tfPathConstraints.gridwidth = 1;
        tfPathConstraints.gridheight = 1;
        tfPathConstraints.weightx = 1;
        tfPathConstraints.fill = GridBagConstraints.HORIZONTAL;
        configPanel.add(tfPath, tfPathConstraints);

        //作者标签
        JLabel labelAuthor = new JLabel("Author:");
        GridBagConstraints labelAuthorConstraints = new GridBagConstraints();
        labelAuthorConstraints.gridx = 1;
        labelAuthorConstraints.gridy = 2;
        labelAuthorConstraints.gridwidth = 1;
        labelAuthorConstraints.gridheight = 1;
        configPanel.add(labelAuthor, labelAuthorConstraints);

        //作者编辑框
        tfAuthor = new JTextField();
        tfAuthor.setText(author);
        GridBagConstraints tfAuthorAuthorConstraints = new GridBagConstraints();
        tfAuthorAuthorConstraints.gridx = 2;
        tfAuthorAuthorConstraints.gridy = 2;
        tfAuthorAuthorConstraints.gridwidth = 1;
        tfAuthorAuthorConstraints.gridheight = 1;
        tfAuthorAuthorConstraints.weightx = 1;
        tfAuthorAuthorConstraints.fill = GridBagConstraints.HORIZONTAL;
        configPanel.add(tfAuthor, tfAuthorAuthorConstraints);

        //刷新按钮
        JButton btnRefresh = new JButton("刷新");
        GridBagConstraints btnRefreshConstraints = new GridBagConstraints();
        btnRefreshConstraints.gridx = 3;
        btnRefreshConstraints.gridy = 2;
        btnRefreshConstraints.gridwidth = 1;
        btnRefreshConstraints.gridheight = 1;
        configPanel.add(btnRefresh, btnRefreshConstraints);
        btnRefresh.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                path = tfPath.getText();
                if (path == null || path.isEmpty()) {
                    path = ".";
                }
                author = tfAuthor.getText();
                if (author == null || author.isEmpty()) {
                    ShellUtils.ShellResult shellResult = ShellUtils.runShells("git config user.name");
                    List<String> result = shellResult.getResult();
                    if (result != null && !result.isEmpty()) {
                        author = result.get(0);
                        tfAuthor.setText(author);
                    }
                }

                if (author != null) {
                    loadData();
                }

            }
        });

        //添加表格
        GridBagConstraints tabelConstraints = new GridBagConstraints();
        tabelConstraints.gridx = 1;
        tabelConstraints.gridy = 2;
        tabelConstraints.gridwidth = 1;
        tabelConstraints.gridheight = 1;
        tabelConstraints.weightx = 1;
        tabelConstraints.weighty = 1;
        //tabelConstraints.insets = new Insets(8, 8, 8, 8);
        tabelConstraints.fill = GridBagConstraints.BOTH;

        //
        tabelModel = new DefaultTableModel(rows, cols);
        table = new JTable(tabelModel);
        table.setShowGrid(true);
        table.setGridColor(Color.GRAY);
        //套一个scrollPane才能显示表头
        JScrollPane scrollPane = new JScrollPane(table);
        panel.add(scrollPane, tabelConstraints);

        //加载数据
        loadData();


        return panel;
    }

    private void loadData() {
        AppExecutors.getInstance().diskIO().execute(new Runnable() {
            @Override
            public void run() {
                getAllMonthStat();
                tabelModel.setDataVector(rows, cols);
                if (table != null) {
                    table.updateUI();
                }
            }
        });
    }

    /**
     * 12个月的统计汇总
     */
    private void getAllMonthStat() {
        sbs.clear();
        for (int month = 1; month <= 12; month++) {
            getMonthStat(sbs, author, month);
        }


        rows = new Object[sbs.size()][5];
        for (int i = 0; i < sbs.size(); i++) {
            StatBean statBean = sbs.get(i);
            rows[i][0] = statBean.author;
            rows[i][1] = statBean.month;
            rows[i][2] = statBean.addedLines;
            rows[i][3] = statBean.removedLines;
            rows[i][4] = statBean.totalLines;
        }
    }

    /**
     * 用户某个月的统计
     *
     * @param sbs
     * @param author 提交者
     * @param month  月份
     */
    private void getMonthStat(java.util.List<StatBean> sbs, String author, int month) {
        Date date = new Date();
        date.setTime(System.currentTimeMillis());
        int year = date.getYear() + 1900;
        String sinceDateStr = String.format("%d-%02d-01", year, month);
        String untilDateStr = String.format("%d-%02d-28", year, month);

        String cmd = "git log --author=" + author + " --since=" + sinceDateStr + " --until=" + untilDateStr + " --pretty=tformat: --numstat | awk '{ add += $1; subs += $2; loc += $1 - $2 } END { printf \"added lines: %s, removed lines: %s, total lines: %s\\n\", add, subs, loc }'";
        String cmdCd = "cd " + path;

        ShellUtils.ShellResult shellResult = ShellUtils.runShells(cmdCd, cmd);
        List<String> result = shellResult.getResult();
        for (String s : result) {
            String[] split = s.split(",");
            for (int i = 0; i < split.length; i++) {
                split[i] = split[i].trim();
            }
            StatBean sb = new StatBean();
            sb.author = author;
            sb.month = month;
            for (String ss : split) {
                if (ss.contains("added lines:")) {
                    String trim = ss.substring("added lines:".length(), ss.length()).trim();
                    if (trim != null && !trim.isEmpty()) {
                        sb.addedLines = Integer.valueOf(trim);
                    } else {
                        sb.addedLines = 0;
                    }
                }

                if (ss.contains("removed lines:")) {
                    String trim = ss.substring("removed lines:".length(), ss.length()).trim();
                    if (trim != null && !trim.isEmpty()) {
                        Logger.v(trim);
                        sb.removedLines = Integer.valueOf(trim);
                    } else {
                        sb.removedLines = 0;
                    }
                }

                if (ss.contains("total lines:")) {
                    String trim = ss.trim().substring("total lines:".length(), ss.length()).trim();
                    if (trim != null && !trim.isEmpty()) {
                        Logger.v(trim);
                        sb.totalLines = Integer.valueOf(trim);
                    } else {
                        sb.totalLines = 0;
                    }
                }
            }
            sbs.add(sb);
        }
    }
}
